<template>
  <div>
    <div id="search-options">
        <el-form size="small" :inline="true">
          <el-form-item label="用户名：">
            <el-input  v-model="searchForm.userName" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色：">
            <el-select v-model="searchForm.roleIds" :multiple="true" :multiple-limit="1">
              <el-option v-for="(obj,index) in roleList" :key="index" :value="obj.id" :label="obj.title"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input  v-model="searchForm.nickName" clearable></el-input>
          </el-form-item>
          <el-form-item label="是否启用：">
            <el-select  v-model="searchForm.isEnabled" clearable>
              <el-option value="yes" label="是"></el-option>
              <el-option value="no" label="否"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="small" id="query-btn" plain icon="el-icon-search" type="primary" @click="searchData">查询</el-button>
            <el-button size="small" id="add-btn" plain icon="el-icon-plus" type="primary" @click="openSaveDialog('add')">添加</el-button>
          </el-form-item>
        </el-form>
    </div>
    <div style="margin-left:20px;margin-right:20px;">
        <el-table id="data-table" :data="userVO" style="width: 100%;" border :highlight-current-row="true" stripe>
            <el-table-column type="expand" width="30px">
              <template slot-scope="props">
                  <el-form label-position="left" inline class="table-expand">
                    <el-form-item label="邮箱："><span>{{props.row.email}}</span> </el-form-item>
                    <el-form-item label="qq："> <span>{{ props.row.qq }}</span> </el-form-item>
                    <el-form-item label="最近修改密码："> <span>{{ props.row.lastUpdatePassTime | datefmt('YYYY-MM-DD HH:mm:ss')}}</span> </el-form-item>
                    <el-form-item label="修改时间："> <span>{{ props.row.updateTime | datefmt('YYYY-MM-DD HH:mm:ss') }}</span> </el-form-item>
                    <el-form-item label="头像：">
                       <img  v-if="props.row.avatar" :src="props.row.avatar" style="width:50px;height:50px;">
                       <span v-else>暂无</span>
                    </el-form-item>
                  </el-form>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="id" align="center"></el-table-column>
            <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
            <el-table-column prop="nickName" label="昵称" align="center"></el-table-column>
            <el-table-column prop="roleList" label="角色" align="center" width="140">
              <template slot-scope="scope">
                <el-tag style="margin-top:3px;width:110px!important;text-align:center;" type="info"
                  v-for="(obj,index) in scope.row.roleList"
                  :key="index">
                    <span>{{obj.title}}</span>
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="genderName" label="性别" align="center"></el-table-column>
            <el-table-column prop="isEnabledName" label="是否启用" align="center" width="110">
              <template slot-scope="scope">
                <el-switch
                      v-model="scope.row.isEnabled"
                      active-value="yes"
                      inactive-value="no"
                      active-color="#13ce66"
                      inactive-text="否"
                      active-text="是"
                      v-on:change="toggleStatus(scope.row.id)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160">
                <template slot-scope="scope">
                    <span>{{ scope.row.createTime | datefmt('YYYY-MM-DD HH:mm:ss') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="230px" align="center">
                 <template slot-scope="scope">
                   <el-tooltip  effect="dark" content="编辑" placement="bottom-end">
                    <el-button size="small" plain  icon="el-icon-edit" type="primary"  @click="openSaveDialog('edit',scope.row)"></el-button>
                   </el-tooltip>
                   <el-tooltip  effect="dark" content="绑定角色" placement="bottom-end">
                    <el-button size="small" plain  icon="el-icon-setting" type="primary"  @click="openRoleDialog(scope.row.id)"></el-button>
                   </el-tooltip>
                 <!--   <div style="margin-top:3px;">
                    <el-button plain icon="el-icon-delete" type="danger" v-on:click="del(scope.row.id)">删除</el-button>
                   </div> -->
                   <el-tooltip  effect="dark" content="重置密码" placement="bottom-end">
                    <el-button size="small" plain  class="el-icon-refresh" type="primary" v-on:click="resetPwd(scope.row.id)"></el-button>
                   </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="pagination">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="searchForm.page.pageNum" :page-sizes="[10]" :page-size="10" :total="common.page.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>

    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogFormVisible" :center="true" v-el-drag-dialog @dragDialog="handleDrag">
        <el-form :model="saveUserForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-input style="width:80%;" v-model="saveUserForm.userName" autocomplete="off" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">  
              <el-form-item label="角色：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-select style="width:80%;" v-model="saveUserForm.roleIds" multiple>
                  <el-option v-for="(obj,index) in roleList" :key="index" :value="obj.id" :label="obj.title"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">  
              <el-form-item label="昵称：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-input  style="width:80%;" v-model="saveUserForm.nickName" autocomplete="off" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">  
              <el-form-item label="电子邮箱：" label-width="120px">
                <span style="width:20%;">&nbsp;</span>
                <el-input  style="width:80%;" v-model="saveUserForm.email" autocomplete="off" clearable></el-input>
              </el-form-item>
            </el-col>  
          </el-row>
          <el-row>
            <el-col :span="12">  
              <el-form-item label="性别：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-select  style="width:80%;" v-model="saveUserForm.gender" autocomplete="off" clearable>
                  <el-option value="man" label="男"></el-option>
                  <el-option value="woman" label="女"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">  
              <el-form-item label="qq：" label-width="120px">
                <span style="width:20%;">&nbsp;</span>
                <el-input  style="width:80%;" v-model="saveUserForm.qq" autocomplete="off" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">  
              <el-form-item label="是否启用：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-select style="width:80%;" v-model="saveUserForm.isEnabled">
                  <el-option value="yes" label="是"></el-option>
                  <el-option value="no" label="否"></el-option>
                </el-select>
              </el-form-item>
            </el-col>  
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="!saveUserForm.id" label="密码：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-input show-password type="password" style="width:80%;" v-model="saveUserForm.password" autocomplete="off" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="!saveUserForm.id" label="确认密码：" label-width="120px" required>
                <span style="color:red;width:20%;">&nbsp;</span>
                <el-input show-password type="password" style="width:80%;" v-model="saveUserForm.confirmPassword" autocomplete="off" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>  
          <!-- <el-row>
            <el-form-item  label="头像：" label-width="120px">
              <span style="width:20%;">&nbsp;</span>
              <el-upload
                class="avatar-uploader"
                action="api/file/minio/uploadPicture"
                :headers="headerContent"
                name="file"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-row> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" plain icon="el-icon-close" type="info" @click="dialogFormVisible = false">取 消</el-button>
          <el-button size="small" plain icon="el-icon-check" type="primary" @click="saveData">确 定</el-button>
        </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" title="设置角色" :visible.sync="roleDialogVisible" :center="true" v-el-drag-dialog @dragDialog="handleDrag">
        <el-form :model="bindRolesForm">
          <el-form-item label="角色：" label-width="120px" required>
            <span style="color:red;width:20%;">&nbsp;</span>
            <el-select style="width:80%;" v-model="bindRolesForm.roleIdList" multiple>
              <el-option v-for="(obj,index) in roleList" :key="index" :value="obj.id" :label="obj.title"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" plain icon="el-icon-close" type="info" @click="roleDialogVisible = false">取 消</el-button>
          <el-button size="small" plain icon="el-icon-check" type="primary" @click="bindRoles">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { getToken } from '@/utils/auth'

export default {
  name: 'elDragDialog',
  directives: { elDragDialog },
  data () {
    return {
        userVO: [{
            id: null,
            userName: '',
            nickName: '',
            email: '',
            avatar: '',
            gender: null,
            genderName: '',
            qq: '',
            isEnabledName: '',
            createTime: '',
            lastUpdatePassTime: '',
            updateTime: '',
            roleList: []
        }],
        searchForm: {
            userName: '',
            nickName: '',
            isEnabled: '',
            roleIds: [],
            page: {
                pageNum: 1,
                pageSize: 10
            }
        },
        dialogTitle: '',
        dialogFormVisible: false,
        dialogImageUrl: '',
        saveUserForm: {
            id: null,
            userName: '',
            nickName: '',
            avatar: '',
            email: '',
            gender: 'man',
            qq: '',
            isEnabled: 'yes',
            password: '',
            confirmPassword: '',
            roleIds: []
        },
        roleDialogVisible: false,
        bindRolesForm: {
          userId: null,
          roleIdList: []
        },
        roleList: [{
          id: null,
          name: '',
          title: ''
        }],
        headerContent: {},
    }
  },
  methods: {
       // v-el-drag-dialog onDrag callback function
      handleDrag() {
        //   console.log('123')
      },
      handleSizeChange (pageSize) {
        this.searchForm.page.pageSize = pageSize
        this.loadData()
      },
      handleCurrentChange (pageNum) {
        this.searchForm.page.pageNum = pageNum
        this.loadData()
      },
      loadData () {
          let vm = this
          vm.$http.post('api/user/find',vm.searchForm).then(res => {
            // console.log(res)
            if (res.data.code === 0){
              //console.log(res.data.data)
              vm.userVO = res.data.data.records
              vm.common.page.total = res.data.data.total
            }
            else {
              vm.$message.error(res.data.msg)
            }
          })
      },
      loadRoles () {
        let vm = this
        vm.$http.post('api/role/findList').then(res => {
          if (res.data.code === 0){
            vm.roleList = res.data.data
          }
          else {
            vm.$message.error(res.data.msg)
          }
        })
      },
      searchData () {
          let vm = this
          vm.searchForm.page.pageNum = 1
          vm.loadData()
      },
      toggleStatus(id){
        let vm = this
        vm.$http.get('api/user/toggleIsEnabled?userId=' + id).then(res => {
          if (res.data.code === 0){
              vm.$message.success('切换成功')
          }
          else {
            vm.$message.error(res.data.msg)
          }
        })
      },
      resetForm () {
       this.saveUserForm = {
            id: null,
            userName: '',
            avatar: '',
            nickName: '',
            email: '',
            gender: 'man',
            qq: '',
            isEnabled: 'yes',
            password: '',
            confirmPassword: '',
            roleIds: []
        }
      },
      findDetail (id) {
        let vm = this
        vm.$http.get('api/user/findOne/' + id).then(res => {
            if (res.data.code === 0){
             vm.saveUserForm = res.data.data
             vm.dialogImageUrl = vm.saveUserForm.avatar
             let index
             vm.saveUserForm.roleIds = []
             for (index in res.data.data.roleList) {
                vm.saveUserForm.roleIds.push(res.data.data.roleList[index].id)
             }
            }
            else {
             vm.$message.error(res.data.msg)
            }
        })
      },
      openSaveDialog (opt,row) {
        let vm = this
        vm.resetForm()
        if('edit' === opt) {
           vm.dialogTitle = '修改'
           vm.findDetail(row.id)
          //  console.log(vm.saveUserForm)
           vm.dialogFormVisible = true
        }
        else if ('add' === opt) {
            vm.dialogTitle = '添加'
            vm.dialogImageUrl = '' // 不然,先点编辑后添加会有编辑时的头像
            vm.dialogFormVisible = true
        }
      },
      saveData () {
          let vm = this
         /*  console.log(vm.saveUserForm.id)
          return */
          // 添加
          if (vm.saveUserForm.id === null) {
            vm.$http.post('api/user/add',vm.saveUserForm).then(res => {
              if (res.data.code === 0){
                  vm.$message({
                      message: '添加用户成功',
                      type: 'success'
                  })
                  vm.dialogFormVisible = false
                  vm.loadData()
              }
              else {
                vm.$message.error(res.data.msg)
              }
            })
          }
          else {
             vm.$http.post('api/user/update',vm.saveUserForm).then(res => {
              if (res.data.code === 0){
                  vm.$message({
                      message: '修改用户成功',
                      type: 'success'
                  })
                  vm.dialogFormVisible = false
                  vm.loadData()
              }
              else {
                vm.$message.error(res.data.msg)
              }
            })
          }

      },
      openRoleDialog (id) {
        let vm = this
        vm.bindRolesForm.userId = id
        vm.$http.get('api/role/findRoleIdsByUserId/' + id).then(res => {
          if (res.data.code === 0){
            vm.bindRolesForm.roleIdList = res.data.data
            vm.roleDialogVisible = true
          }
          else {
            vm.$message.error(res.data.msg)
          }
        })
      },
      bindRoles () {
        let vm = this
        vm.$http.post('api/user/bindRoles',vm.bindRolesForm).then(res => {
          if (res.data.code === 0){
              vm.$message.success('设置角色成功')
              vm.roleDialogVisible = false
              vm.loadData()
          }
          else {
            vm.$message.error(res.data.msg)
          }
        })
      },
      resetPwd (id) {
        let vm = this
        vm.$http.get('api/user/resetPwd?userId=' + id).then(res => {
          if (res.data.code === 0){
              vm.$message.success('重置密码成功')
              vm.loadData()
          }
          else {
            vm.$message.error(res.data.msg)
          }
        })
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        // console.log(res)
        let vm = this
        vm.saveUserForm.avatar = res.data.url
        vm.dialogImageUrl = res.data.url
      }
  },
  mounted() {
    let vm = this
    vm.loadData()
    vm.loadRoles()
  },
  beforeMount () {
    let vm = this
    vm.headerContent = { 'Authorization': getToken() }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
</style>